package cn.conac.rc.gateway.modules.ofs.rest;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.conac.rc.framework.utils.RestClientException;
import cn.conac.rc.gateway.base.ResultPojo;
import cn.conac.rc.gateway.modules.common.service.UserExtService;
import cn.conac.rc.gateway.modules.ofs.contsant.Contsants;
import cn.conac.rc.gateway.modules.ofs.entity.OrganizationEntity;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationBaseService;
import cn.conac.rc.gateway.modules.ofs.service.OrganizationService;
import cn.conac.rc.gateway.modules.ofs.vo.OrgLibInfoVo;
import cn.conac.rc.gateway.modules.ofs.vo.OrganizationVo;
import cn.conac.rc.gateway.security.UserUtils;
import cn.conac.rc.gateway.security.vo.JwtUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping(value={"ofs/organization/", "ofs/orgs/"} )
@Api(tags = "部门库信息（主表）", description = "三定信息")
public class OrganizationController {

	@Autowired
	OrganizationService service;
	
//	@Autowired
//	CodeService  codeService;
	
	@Autowired
	OrganizationBaseService orgBaseService;
	
	@Autowired
	UserExtService  userExtService;

	@ApiOperation(value = "新增", httpMethod = "POST", response = OrganizationVo.class, notes = "保存部门库")
	@RequestMapping(value = "c", method = RequestMethod.POST)
	public Object cudOrgSave(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "保存对象", required = true) @RequestBody JSONObject orgInfo) throws Exception {
		
		ResultPojo resultInfo = new ResultPojo();
		OrganizationEntity orgEntity = new OrganizationEntity();
//		OrganizationEntity parentOrgEntity = new OrganizationEntity();
		orgEntity = JSONObject.toJavaObject(orgInfo, OrganizationEntity.class);
		if( StringUtils.isEmpty(orgEntity.getAreaId())) {
			orgEntity.setAreaId(UserUtils.getCurrentUser().getAreaId());
		}
		if(StringUtils.isEmpty(orgEntity.getAreaCode())) {
			orgEntity.setAreaCode(UserUtils.getCurrentUser().getAreaCode());
		}

		// 创建时默认无子部门
		orgEntity.setHasChild(Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD);
		
		// 部门库创建用户ID
		if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
			orgEntity.setCreateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
		}
		// 部门库创建时间
		orgEntity.setCreateTime(new Date());
		
		 if(StringUtils.isEmpty(orgEntity.getType())) {
				// 选择的主管部门的机构类型为null场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg(ResultPojo.MSG_FAILURE + " 部门类型为null或者空，数据异常。" );
				resultInfo.setResult(null);
				return  resultInfo;
		}
		if(StringUtils.isEmpty(orgEntity.getStatus())) {
				// 选择的主管部门的机构类型为null场合
				resultInfo.setCode(ResultPojo.CODE_FAILURE);
				resultInfo.setMsg(ResultPojo.MSG_FAILURE + " 部门状态为null或者空，数据异常。" );
				resultInfo.setResult(null);
				return  resultInfo;
		}
		 
//		// 判断是否为主管部门
//		//判断该部门的主管部门是否已编码 
//		if(StringUtils.isNotEmpty(orgEntity.getParentId())) {
//			JSONObject parentOrgInfoJson =  service.findById(orgEntity.getParentId());
//			if (ResultPojo.CODE_SUCCESS.equals(parentOrgInfoJson.getString("code")) ) {
//				// 部门库信息取得成功场合
//				parentOrgEntity = JSONObject.toJavaObject(parentOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
//				if(StringUtils.isNotEmpty(parentOrgEntity.getCode())){
//					//主管部门已编码场合，后台对该部门进行自动编码操作
//					// 取得地区码
//					String adminCode = parentOrgEntity.getCode().substring(0, 6);
//					// 取得基本码
//					String basicCode = parentOrgEntity.getCode().substring(6, 9);
//					// 取得部门类型
//					String orgType = orgEntity.getType();
//					// 根据地区码和基本码取得生成的编码
//					JSONObject codeInfoJson = codeService.encode(adminCode, basicCode, orgType);
//					if (ResultPojo.CODE_SUCCESS.equals(codeInfoJson.getString("code")) ) {
//						// 编码成功场合
//						orgEntity.setCode(codeInfoJson.getString("result"));
//					} else {
//						// 编码失败场合
//						resultInfo.setCode(codeInfoJson.getString("code"));
//						resultInfo.setMsg("[codeService.encode(organization)] in function of save" + 
//									ResultPojo.MSG_FAILURE + "【"  + codeInfoJson.getString("msg") + "】" );
//						resultInfo.setResult(null);
//						return resultInfo;
//					}
//				} 
//			} else {
//				// 部门库信息取得失败场合
//				resultInfo.setCode(parentOrgInfoJson.getString("code"));
//				resultInfo.setMsg("[service.findById(organization)] in function of save (currentOrgId="  +
//						orgEntity.getParentId()+ " error occured) " + ResultPojo.MSG_FAILURE + "【"  + parentOrgInfoJson.getString("msg") + "】" );
//				resultInfo.setResult(null);
//				return resultInfo;
//			}
//		}
		
		JSONObject  orgInfoJsonObj = (JSONObject)JSONObject.toJSON(orgEntity); 
		
		return  service.saveOrUpdate(orgInfoJsonObj);
	}

	@ApiOperation(value = "物理删除", httpMethod = "POST", response = OrganizationVo.class, notes = "根据id物理删除资源")
	@RequestMapping(value = "{id}/d", method = RequestMethod.POST)
	public JSONObject cudOrgDelete(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "id", required = true) @PathVariable("id") String id) {
		
		// 将该部门库关联的用户信息中的部门库ID置空
		JSONObject userExtJsonObj =  userExtService.updateOrgIdToNull(id);
		JSONObject  ofsJsonObj = null;
		if (ResultPojo.CODE_SUCCESS.equals(userExtJsonObj.getString("code")) ) {
			// 删除部门库信息及相应的三定信息
			 ofsJsonObj =  service.delete(id);
			if (ResultPojo.CODE_SUCCESS.equals(ofsJsonObj.getString("code")) ) {
				// TODO 删除关联该部门库ID的权力清单信息
				
				// TODO 删除关联该部门库ID的责任清单信息
				
			} else {
				//TODO 恢复置空的orgId
			}
			return  ofsJsonObj;
		} else {
			return  userExtJsonObj;
		}
	}
	
	@ApiOperation(value = "更新", httpMethod = "POST", response = OrganizationVo.class, notes = "更新部门库")
	@RequestMapping(value = "{orgId}/u", method = RequestMethod.POST)
	public Object cudOrgUpdate(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "更新对象", required = true) @RequestBody JSONObject orgInfo) {
		
		ResultPojo resultInfo = new ResultPojo();
		OrganizationEntity orgEntity = new OrganizationEntity();
		Map<String,String> idOwnSysMap = new HashMap<String, String>();
		int ret = 0;
		orgEntity = JSONObject.toJavaObject(orgInfo, OrganizationEntity.class);
		
		// 确保ID不能为空
		if(StringUtils.isEmpty(orgEntity.getId())) {
			// ID为空场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("更新场合部门库的ID不能为null或者空【 ID = " + orgEntity.getId() + "】");
			resultInfo.setResult(null);
			return resultInfo;
		}
		
		// 确保所属系统不能为空
		if(StringUtils.isEmpty(orgEntity.getOwnSys())) {
			// 所属系统为空场合
			resultInfo.setCode(ResultPojo.CODE_FAILURE);
			resultInfo.setMsg("部门库的所属系统不能为null或者空【 ownsys = " + orgEntity.getOwnSys() + "】");
			resultInfo.setResult(null);
			return resultInfo;
		}
		// 部门库创建用户ID
		if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
			orgEntity.setUpdateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
		}
		// 部门库创建时间
		orgEntity.setUpdateTime(new Date());
		
		JSONObject dbOrgInfoJson =  service.findById(orgEntity.getId());
		OrganizationEntity dbOrgEntity = new OrganizationEntity();

		if (ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code")) ) {
			// 部门库信息取得成功场合
			dbOrgEntity = JSONObject.toJavaObject(dbOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
			orgEntity.setCreateTime(dbOrgEntity.getCreateTime());
			orgEntity.setCreateUserId(dbOrgEntity.getCreateUserId());
		}
		// 1、 当前部门是主管部门场合-子部门更新场合
		// 主管部门的场合并且更改了所属系统场合，递归更新子部门的所属系统
		if(StringUtils.isEmpty(orgEntity.getParentId()) && Contsants.OFS_ORG_STR_IS_COMP.equals(orgEntity.getIsComp())) {
			// 判断是不是更改了所属系统
			if (ResultPojo.CODE_SUCCESS.equals(dbOrgInfoJson.getString("code")) ) {
				// 部门库信息取得成功场合
				// 当前的所属系统与db中的所属系统不同
				if(!orgEntity.getOwnSys().equals(dbOrgEntity.getOwnSys())) {
					// 递归更新子部门的所属系统(部门库和部门基本信息表两张表)
					ret =recUpdateOwnSys(orgEntity.getId(), orgEntity.getOwnSys(),idOwnSysMap,resultInfo);
					if(ret != 0) {
						return resultInfo;
					}
				}
			}
		}
		
//		// 是否有下设部门更新
//		JSONObject orgInfoJsonResult =   service.findChildOrgs(orgEntity.getId());
//		// 注意result包了两层
//		JSONArray orgInfoJsonList =   orgInfoJsonResult.getJSONArray("result");
//		JSONObject orgInfoJsonObj = null;
//		String hasChild = Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD;
//		for (int i=0; i < orgInfoJsonList.size(); i ++) {
//			orgInfoJsonObj = orgInfoJsonList.getJSONObject(i);
//			if(Contsants.OFS_ORGANIZATION_FLAG_NORMAL.equals(orgInfoJsonObj.getString("status")) ||
//					Contsants.OFS_ORGANIZATION_FLAG_CANCEL.equals(orgInfoJsonObj.getString("status"))) {
//				hasChild = Contsants.OFS_ORGANIZATION_FLAG_HAS_CHILD;
//				break;
//			}
//		}
		// 设置为默认的值（ofs更新时会根据数据库相关值更改其值）
		orgEntity.setHasChild(Contsants.OFS_ORGANIZATION_FLAG_HAS_NO_CHILD);
		
//		// 2、当前部门不是主管部门或者是主管部门场合的更新
//		// 判断要更新的部门是否已经编码
//		if(StringUtils.isEmpty(orgEntity.getCode())) {
//			// 判断是否为主管部门
//			//判断该部门的主管部门是否已编码 
//			if(StringUtils.isNotEmpty(orgEntity.getParentId())) {
//				
//				JSONObject parentOrgInfoJson =  service.findById(orgEntity.getParentId());
//				if (ResultPojo.CODE_SUCCESS.equals(parentOrgInfoJson.getString("code")) ) {
//					// 部门库信息取得成功场合
//					OrganizationEntity parentOrgEntity = new OrganizationEntity();
//					parentOrgEntity = JSONObject.toJavaObject(parentOrgInfoJson.getJSONObject("result"), OrganizationEntity.class);
//					if(StringUtils.isNotEmpty(parentOrgEntity.getCode())) {
//						//主管部门已编码场合，后台对该部门进行自动编码操作
//						// 取得地区码
//						String adminCode = parentOrgEntity.getCode().substring(0, 6);
//						// 取得基本码
//						String basicCode = parentOrgEntity.getCode().substring(6, 9);
//						// 取得部门类型
//						String orgType = orgEntity.getType();
//						// 根据地区码和基本码取得生成的编码
//						JSONObject codeInfoJson = codeService.encode(adminCode, basicCode, orgType);
//						if (ResultPojo.CODE_SUCCESS.equals(codeInfoJson.getString("code")) ) {
//							// 编码成功场合
//							orgEntity.setCode(codeInfoJson.getString("result"));
//						} else {
//							// 编码失败场合
//							resultInfo.setCode(codeInfoJson.getString("code"));
//							resultInfo.setMsg("[codeService.encode(organization)] in function of update" + 
//										ResultPojo.MSG_FAILURE + "【"  + codeInfoJson.getString("msg") + "】" );
//							resultInfo.setResult(null);
//							return resultInfo;
//						}
//					} 
//				} else {
//					// 部门库信息取得失败场合
//					resultInfo.setCode(parentOrgInfoJson.getString("code"));
//					resultInfo.setMsg("[service.findById(organization)] in function of update (currentOrgId="  +
//							orgEntity.getParentId()+ " error occured) " + ResultPojo.MSG_FAILURE + "【"  + parentOrgInfoJson.getString("msg") + "】" );
//					resultInfo.setResult(null);
//					return resultInfo;
//				}
//			} 
//			// 
//			JSONObject  orgInfoJsonObj = (JSONObject)JSONObject.toJSON(orgEntity);
//			return service.saveOrUpdate(orgInfoJsonObj);
//		} else {
//			// 已经编码的场合直接更新
//			return service.saveOrUpdate(orgInfo);
//		}
		JSONObject  orgInfoJsonObjSave = (JSONObject)JSONObject.toJSON(orgEntity); 
		return service.saveOrUpdate(orgInfoJsonObjSave);
		
	}
	
	@ApiOperation(value = "详情", httpMethod = "GET", response = OrganizationVo.class, notes = "根据id获取资源详情")
	@RequestMapping(value = "{orgId}/r", method = RequestMethod.GET)
	public JSONObject orgFindById(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId) {
		
		return service.findById(orgId);
	}
	
	@ApiOperation(value = "详情", httpMethod = "GET", response = OrganizationVo.class, notes = "根据id获取资源详情")
	@RequestMapping(value = "lib/{orgId}/r", method = RequestMethod.GET)
	public JSONObject findOrgLibById(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId) {
		return service.findOrgLibById(orgId);
	}
	
	@ApiOperation(value = "详情(兼容三定信息及app)", httpMethod = "GET", response = OrganizationVo.class, notes = "根据id获取资源详情")
	@RequestMapping(value = "{orgId}", method = RequestMethod.GET)
	public JSONObject orgFindById2(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "orgId", required = true) @PathVariable("orgId") String orgId) {
		
		return service.findById(orgId);
	}

//	// 部门库赋码
//	@ApiOperation(value = "部门库赋码", httpMethod = "POST", response = String.class, notes = "部门库赋码")
//	@RequestMapping(value = "{orgId}/encode", method = RequestMethod.POST)
//	public Object encode(HttpServletRequest request, HttpServletResponse response,
//			@ApiParam(value = "地区码(areaCode)和基本码(basicCode)的map", required = true)  @RequestBody Map<String, String> codeMap,
//			@ApiParam(value = "部门库的Id", required = true) @PathVariable(value = "orgId")  String orgId) {
//		int ret = 0;
//		ResultPojo resultInfo = new ResultPojo();
//		Map<String,String> idCodeMap = new HashMap<String, String>();
//		OrganizationEntity orgEntity = new OrganizationEntity();
//		// 取得地区码
//		String adminCode = codeMap.get("adminCode");
//		// 取得基本码
//		String basicCode = codeMap.get("basicCode");
//		
//		// 判断当前要赋码的部门为不能是撤并的部门
//		 // 根据orgID取得部门库详细信息
//		JSONObject orgInfoJson =  service.findById(orgId);
//		if (ResultPojo.CODE_SUCCESS.equals(orgInfoJson.getString("code")) ) {
//			// 部门库信息取得成功场合
//			orgEntity = JSONObject.toJavaObject(orgInfoJson.getJSONObject("result"), OrganizationEntity.class);
//			
//			if(Contsants.OFS_ORGANIZATION_FLAG_CANCEL.equals(orgEntity.getStatus())){
//				// 选择的部门为撤并部门
//				resultInfo.setCode(ResultPojo.CODE_FAILURE);
//				resultInfo.setMsg(ResultPojo.MSG_FAILURE + " 选择的该部门是撤并的部门，不能进行赋码操作。");
//				resultInfo.setResult(null);
//				return resultInfo;
//			} else if(!(Contsants.OFS_ORG_STR_IS_COMP.equals(orgEntity.getIsComp()) && StringUtils.isEmpty(orgEntity.getParentId()))) {
//				// 判断当前要赋码的部门必须为主管部门并且该部门的parentId为null
//				resultInfo.setCode(ResultPojo.CODE_FAILURE);
//				resultInfo.setMsg(ResultPojo.MSG_FAILURE + " 选择的该部门不是主管部门，不能进行赋码操作。");
//				resultInfo.setResult(null);
//				return resultInfo;
//			} 
//		} else {
//			// 部门库信息取得失败场合
//			resultInfo.setCode(orgInfoJson.getString("code"));
//			resultInfo.setMsg("[service.findById(organization)] in function of encode (currentOrgId="  +
//						orgId+ " error occured) " + ResultPojo.MSG_FAILURE + "【"  + orgInfoJson.getString("msg") + "】" );
//			resultInfo.setResult(idCodeMap);
//			return resultInfo;
//		}
//		
//		// 校验选择的基本码是否被该地区的使用过,通过（adminCode+basicCode）在部门编码表中进行查找
//		String findId = adminCode +basicCode;
//		JSONObject  codeInfoJson = codeService.findByFindId(findId);
//		if (ResultPojo.CODE_SUCCESS.equals(codeInfoJson.getString("code")) ) {
//			JSONObject codeJsonObj	= codeInfoJson.getJSONObject("result");
//			if(null !=codeJsonObj ){
//				resultInfo.setCode(ResultPojo.RET_CODE_PARAM_ERR_5001);
//				resultInfo.setMsg(ResultPojo.RET_MSG_PARAM_ERR_5001);
//				resultInfo.setResult(null);
//				return resultInfo;
//			}
//		}
//		
//		ret = recEncode(orgId, adminCode, basicCode,idCodeMap,resultInfo);
//		if(ret == 0) {
//			resultInfo.setCode(ResultPojo.CODE_SUCCESS);
//			resultInfo.setMsg(ResultPojo.MSG_SUCCESS);
//			resultInfo.setResult(idCodeMap);
//		} 
//		return resultInfo;
//	}

	@ApiOperation(value = "获取最近变更的三定信息", httpMethod = "GET", response = OrganizationVo.class, notes = "根据指定数量NUM获取最近变更的三定信息")
	@RequestMapping(value = "organization/recentOrgs", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findRecentOrgs4App(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "数量限制", required = true) @RequestParam("num") int num,
			@ApiParam(value = "地区code", required = true) @RequestParam("areaCode") String areaCode) {
		return new ResponseEntity<ResultPojo>(new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS,
				service.findRecentOrgs4App(num, areaCode)), HttpStatus.OK);
	}

	// 根据参数查询部门库
	@ApiOperation(value = "根据参数查询部门库", httpMethod = "POST", response = OrganizationVo.class, notes = "根据参数查询部门库")
	@RequestMapping(value = "Org/param", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> findOrgByParam(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "根据参数查询部门库", required = false) @RequestBody OrganizationVo vo) {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.findOrgByParam(vo)),
				HttpStatus.OK);
	}

	// 根据父部门标识查询第一级子部门库
	@ApiOperation(value = "根据父部门标识查询第一级子部门库", httpMethod = "GET", response = OrganizationVo.class, notes = "根据父部门标识查询第一级子部门库")
	@RequestMapping(value = "ChildOrgs/{parentId}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findChildOrgs(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门库的父部门标识", required = false) @PathVariable("parentId") String parentId) {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.findChildOrgs(parentId)),
				HttpStatus.OK);
	}
	
	// 统计地区的事业单位和行政机关
	@ApiOperation(value = "查询当前地区的行政机关和事业单位数量", httpMethod = "GET", response = OrganizationVo.class, notes = "查询当前地区的行政机关和事业单位数量，返回值中第一个为行政机关，第二个为事业单位")
	@RequestMapping(value = "CountXZJGAndSYDW/{areaCode}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> CountXZJGAndSYDW(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "区划", required = false) @PathVariable("areaCode") String areaCode) {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.CountXZJGAndSYDW(areaCode)),
				HttpStatus.OK);
	}

	// 统计地区的事业单位和行政机关
	@ApiOperation(value = "查询当地九大系统的树结构", httpMethod = "GET", response = ArrayList.class, notes = "查询当地九大系统的树结构")
	@RequestMapping(value = "orgTree/{areaCode}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findOrgTree(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "区划", required = false) @PathVariable("areaCode") String areaCode) {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.findOrgTree(areaCode)),
				HttpStatus.OK);
	}
	
    //根据id获取机构树信息(包含内设机构、下设机构和事业单位)
    @ApiOperation(value = "根据id获取机构树信息", httpMethod = "GET",  notes = "根据id获取机构树信息")
	@RequestMapping(value = "mapTree/{id}", method = RequestMethod.GET)
	public ResponseEntity<ResultPojo> findMapTreeById(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "机构ID", required = true) @PathVariable("id") String id) {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.findMapTreeById(id)),
				HttpStatus.OK);
    }

	@ApiOperation(value = "根据部门库ID取得部门基本信息", httpMethod = "GET", response = JSONObject.class, notes = "根据部门库ID取得部门基本信息")
	@RequestMapping(value = "{orgId}/base", method = RequestMethod.GET)
	public JSONObject findDetailInfoByOrgId(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "部门基本表id", required = true) @PathVariable("orgId") String orgId)
			throws RestClientException, Exception {
		return service.findOrgDetailByOrgId(orgId);
	}

	// 查询九大系统
	@ApiOperation(value = "查询九大系统", httpMethod = "POST", response = String.class, notes = "查询九大系统")
	@RequestMapping(value = "findOwnSys", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> findOwnSys(HttpServletRequest request, HttpServletResponse response) {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.findOwnSys()), HttpStatus.OK);
	}
	
	@ApiOperation(value = "个数", httpMethod = "POST", response = OrganizationVo.class, notes = "根据条件获得资源数量")
	@RequestMapping(value = "count", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> count(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody OrganizationVo vo) throws Exception {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.count(vo)), HttpStatus.OK);
	}

	@ApiOperation(value = "列表", httpMethod = "POST", response = OrganizationVo.class, notes = "根据条件获得资源列表")
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public ResponseEntity<ResultPojo> list(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody OrganizationVo vo) throws Exception {
		return new ResponseEntity<ResultPojo>(
				new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS, service.list(vo)), HttpStatus.OK);
	}
	
	@ApiOperation(value = "带分页列表", httpMethod = "POST", response = OrganizationVo.class, notes = "根据条件获得部门库列表（带分页信息）")
	@RequestMapping(value = "page", method = RequestMethod.POST)
	public JSONObject pageList(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody OrganizationVo vo) throws Exception {
		return service.list(vo);
	}
	
	@ApiOperation(value = "带分页列表", httpMethod = "POST", response = OrganizationVo.class, notes = "根据条件获得部门库列表（带分页信息）")
	@RequestMapping(value = "lib/page", method = RequestMethod.POST)
	public JSONObject orgLibPageList(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "查询条件对象", required = true) @RequestBody OrgLibInfoVo vo) throws Exception {
		return service.findOrgLibList(vo);
	}
	
//	// 删除多个部门库
//	@ApiOperation(value = "删除部门库", httpMethod = "POST", response = OrganizationVo.class, notes = "删除部门库")
//	@RequestMapping(value = "delete/{ids}", method = RequestMethod.POST)
//	public ResponseEntity<ResultPojo> deleteOrganizationsByIds(HttpServletRequest request, HttpServletResponse response,
//			@ApiParam(value = "一串部门库Id", required = false) @RequestParam(value = "param", required = false) String param) {
//		return new ResponseEntity<ResultPojo>(new ResultPojo(ResultPojo.CODE_SUCCESS, ResultPojo.MSG_SUCCESS,
//				service.deleteOrganizationsByIds(param)), HttpStatus.OK);
//	}
	
	// 部门库调整顺序
	@ApiOperation(value = "部门库调整顺序", httpMethod = "POST", response = String.class, notes = "部门库调整顺序")
	@RequestMapping(value = "order", method = RequestMethod.POST)
	public JSONObject  cudSortOrg(HttpServletRequest request, HttpServletResponse response,
			 @RequestBody Map<String, Object> param) {
		
		return service.sortOrg(param);
	}
	
//	/**
//	 *  使用递归为主管部门及下设机构赋码
//	 * @param orgId  部门库Id
//	 * @param areaCode  区域code
//	 * @param basicCode 基本码
//	 * @param idCodeMap  map<orgId,编码值>
//	 * @param resultInfo  
//	 * @return
//	 */
//	public int  recEncode(String orgId, String areaCode, String basicCode, Map<String, String> idCodeMap, ResultPojo resultInfo ) {
//		
//		int ret = 0;
//		int saveFlag = 0;
//		String codeStr = null;
//		OrganizationEntity orgEntity = new OrganizationEntity();
//		JSONObject  childOrgJsonObj = null;
//		String subOrgId = null;
//		
//		 // 根据orgID取得部门库详细信息
//		JSONObject orgInfoJson =  service.findById(orgId);
//		if (ResultPojo.CODE_SUCCESS.equals(orgInfoJson.getString("code")) ) {
//			// 部门库信息取得成功场合
//			orgEntity = JSONObject.toJavaObject(orgInfoJson.getJSONObject("result"), OrganizationEntity.class);
//			 if(StringUtils.isEmpty(orgEntity.getType())) {
//					// 选择的主管部门的机构类型为null场合
//					resultInfo.setCode(ResultPojo.CODE_FAILURE);
//					resultInfo.setMsg(ResultPojo.MSG_FAILURE + " 部门的部门类型为null，数据异常。 (currentOrgId="  + orgId+ " error occured) " );
//					resultInfo.setResult(null);
//					return  -1;
//			 }
//			if(StringUtils.isEmpty(orgEntity.getCode()) && (Contsants.OFS_ORGANIZATION_FLAG_NORMAL.equals(orgEntity.getStatus()))){
//				saveFlag = 1;
//			}
//			// 在赋码同时如果排序号为空场合下将部门库的ID设为排序号
//			
//		} else {
//			// 部门库信息取得失败场合
//			resultInfo.setCode(orgInfoJson.getString("code"));
//			resultInfo.setMsg("[service.findById(organization)] in function of recEncode (currentOrgId="  + orgId+ " error occured) " + ResultPojo.MSG_FAILURE + "【"  + orgInfoJson.getString("msg") + "】" );
//			resultInfo.setResult(idCodeMap);
//			return -1;
//		}
//	
//		// 必须编码或者设置排序号才进行更新操作否则不做任何处理（为撤并部门是也不进行编码）
//		if(saveFlag == 1) {
//			// 为当前机构ID进行赋码操作
//			// 根据地区码和基本码取得生成的编码
//			JSONObject codeInfoJson = codeService.encode(areaCode, basicCode, orgEntity.getType());
//			if (ResultPojo.CODE_SUCCESS.equals(codeInfoJson.getString("code")) ) {
//				// 编码成功场合
//				codeStr =  codeInfoJson.getString("result");
//				if(StringUtils.isEmpty(orgEntity.getCode())) {
//					orgEntity.setCode(codeStr);
//				}
//			} else {
//				// 编码失败场合
//				resultInfo.setCode(codeInfoJson.getString("code"));
//				resultInfo.setMsg("[codeService.encode(organization)] in function of recEncode (currentOrgId="  + orgId+
//											" error occured) " + ResultPojo.MSG_FAILURE + "【"  + codeInfoJson.getString("msg") + "】" );
//				resultInfo.setResult(idCodeMap);
//				return -1;
//			}
//
//			if(StringUtils.isEmpty(orgEntity.getSort())){
//				orgEntity.setSort(orgEntity.getId());
//			}
//			JSONObject  orgInfoJsonObj = (JSONObject)JSONObject.toJSON(orgEntity);
//			// 根据ID更新部门库的编码信息
//			JSONObject organizationInfoJson = service.saveOrUpdate(orgInfoJsonObj);
//			// 判断更新是否成功失败
//			if (ResultPojo.CODE_SUCCESS.equals(organizationInfoJson.getString("code")) ) {
//				// 保存成功场合
//				idCodeMap.put(organizationInfoJson.getJSONObject("result").getString("id"), organizationInfoJson.getJSONObject("result").getString("code"));
//			} else {
//				// 保存失败场合
//				resultInfo.setCode(organizationInfoJson.getString("code"));
//				resultInfo.setMsg("[service.saveOrUpdate(organization)] in function of recEncode (currentOrgId="  + orgId+
//										" error occured) " + ResultPojo.MSG_FAILURE + "【"  + organizationInfoJson.getString("msg") + "】" );
//				resultInfo.setResult(idCodeMap);
//				return -1;
//			}
//		}
//		
//		if(Contsants.OFS_ORGANIZATION_FLAG_NORMAL.equals(orgEntity.getStatus())){
//			// 通过orgId查找下设机构
//			JSONObject childOrgInfoJson   = service.findChildOrgs(orgId);
//			JSONArray childOrgList = childOrgInfoJson.getJSONArray("result");
//			
//			if(childOrgList.isEmpty() == true){
//				return 0;
//			} else {
//				for (int i=0; i < childOrgList.size(); i++) {
//					childOrgJsonObj =  (JSONObject)childOrgList.get(i);
//					subOrgId = childOrgJsonObj.getString("id");
//					ret = recEncode(subOrgId, areaCode,basicCode,idCodeMap,resultInfo);
//					if(ret != 0) {
//						return -1;
//					}
//				}
//			}
//		}
//		return 0;
//	}
//	
	@ApiOperation(value = "委办局根据用户Id查询用的部门树", httpMethod = "GET", response = ArrayList.class, notes = "委办局根据用户Id查询用的部门树")
	@RequestMapping(value = "{userId}/orgTree", method = RequestMethod.GET)
	public JSONObject findOrgTreeByUserId(HttpServletRequest request, HttpServletResponse response,
			@ApiParam(value = "用户Id", required = false) @PathVariable("userId") Integer userId) {
	    JwtUser user = UserUtils.getCurrentUser();
		   if(user.getUserType()<2) {
			   return service.findOrgTree(UserUtils.getCurrentUser().getAreaCode());
		   } else {
			   return service.findOrgTreeByUserId(userId);
		   }
	}
	
	@ApiOperation(value = "检查所输入的部门库名称是否已经存在", httpMethod = "POST", response = String.class, notes = "根据区域code和部门库名称检查所输入的部门库名称是否已经存在")
	@RequestMapping(value = "check/name", method = RequestMethod.POST)
	public JSONObject  checkOrgName(HttpServletRequest request, HttpServletResponse response,
			 @RequestBody Map<String, Object> condMap) {
		return service.checkOrgName(condMap);
	}
	
	/**
	 *  使用递归为下设机构更新所属系统
	 * @param orgId  部门库Id
	 * @param resultInfo  
	 * @return
	 */
	public int  recUpdateOwnSys(String orgId, String ownSys, Map<String, String> idOwnSysMap, ResultPojo resultInfo ) {
		
		int ret = 0;
		OrganizationEntity subOrgEntity = new OrganizationEntity();
		JSONObject  childOrgJsonObj = null;
		JSONObject  subOrgInfoJsonObj = null;
		String subOrgId = null;
		JSONArray childOrgList  = new JSONArray();
		
		// 通过orgId查找下设机构
		JSONObject childOrgInfoJson   = service.findChildOrgs(orgId);
		if (ResultPojo.CODE_SUCCESS.equals(childOrgInfoJson.getString("code")) ) {
			childOrgList = childOrgInfoJson.getJSONArray("result");
		} else {
			// 取得下设机构失败场合
			resultInfo.setCode(childOrgInfoJson.getString("code"));
			resultInfo.setMsg("[service.findChildOrgs] in function of recUpdateOwnSys (currentOrgId="  + orgId+
									" error occured) " + ResultPojo.MSG_FAILURE + "【"  + childOrgInfoJson.getString("msg") + "】" );
			resultInfo.setResult(idOwnSysMap);
			return -1;
		}
		if(childOrgList.isEmpty() == true){
			return 0;
		} else {
			for (int i=0; i < childOrgList.size(); i++) {
				
				childOrgJsonObj =  (JSONObject)childOrgList.get(i);
				
				// 更新下设机构的所属系统
				subOrgEntity = JSONObject.toJavaObject(childOrgJsonObj, OrganizationEntity.class);
				subOrgEntity.setOwnSys(ownSys);
				// 部门库创建用户ID
				if(StringUtils.isNotEmpty(UserUtils.getCurrentUser().getId())) {
					subOrgEntity.setUpdateUserId(Integer.valueOf(UserUtils.getCurrentUser().getId()));
				}
				// 部门库创建时间
				subOrgEntity.setUpdateTime(new Date());
				subOrgInfoJsonObj = (JSONObject)JSONObject.toJSON(subOrgEntity);
				JSONObject updateOrgInfoJson = service.saveOrUpdate(subOrgInfoJsonObj);
				 // 判断保存是否成功失败
				 if (!ResultPojo.CODE_SUCCESS.equals(updateOrgInfoJson.getString("code")) ) {
					  // 保存失败场合
					  resultInfo.setCode(updateOrgInfoJson.getString("code"));
					  resultInfo.setMsg("[service.saveOrUpdate] in function of recUpdateOwnSys " + ResultPojo.MSG_FAILURE + "【"  + updateOrgInfoJson.getString("msg") + "】" );
					  resultInfo.setResult(null);
					  return  -1;
				 } 
				subOrgId = childOrgJsonObj.getString("id");
				idOwnSysMap.put(subOrgId, ownSys);
				// 如果部门库中baseID不为空场合下，将部门基本信息表中的所属系统也一并更新
//				if(StringUtils.isNotEmpty(subOrgEntity.getBaseId())) {
//					// 部门基本信息表中的所属系统也一并更新
//					 OrganizationBaseEntity baseEntityInfo = new OrganizationBaseEntity();
//				     JSONObject baseInfoJson = orgBaseService.findById(subOrgEntity.getBaseId());
//				     if (ResultPojo.CODE_SUCCESS.equals(baseInfoJson.getString("code"))) {
//				    	 baseEntityInfo =   JSONObject.toJavaObject(baseInfoJson.getJSONObject("result"), OrganizationBaseEntity.class);
//				    	 baseEntityInfo.setOwnSys(ownSys);
//				      } else {
//				    	  resultInfo.setCode(baseInfoJson.getString("code"));
//				    	  resultInfo.setMsg( "部门基本信息表中以主键ID 【" + subOrgEntity.getBaseId()  + "】的" +  baseInfoJson.getString("msg"));
//				    	  resultInfo.setResult(null);
//				          return -1;
//				     }
//					 // 执行保存部门基本信息表
//				     JSONObject updateBaseInfoJson = orgBaseService.saveOrUpdate(baseEntityInfo, "1");
//			    	 // 判断保存是否成功失败
//					  if (!ResultPojo.CODE_SUCCESS.equals(updateBaseInfoJson.getString("code")) ) {
//						  // 保存失败场合
//						  resultInfo.setCode(updateBaseInfoJson.getString("code"));
//						  resultInfo.setMsg("[orgBaseService.saveOrUpdate] in function of recUpdateOwnSys " + ResultPojo.MSG_FAILURE + "【"  + updateBaseInfoJson.getString("msg") + "】" );
//						  resultInfo.setResult(null);
//						  return  -1;
//					  } 
//				}
				// 递归更新下设机构的下设机构的所属系统
				ret = recUpdateOwnSys(subOrgId, ownSys, idOwnSysMap, resultInfo);
				if(ret != 0) {
					return -1;
				}
			}
		}
		return 0;
	}
	
//	/**
//	 * 部门库的相关字段同步更新到部门基本信息表
//	 * @param orgEntity
//	 * @param resultInfo
//	 * @return 0： 正常 -1 错误
//	 */
//	public int updateBaseInfo(OrganizationEntity orgEntity, ResultPojo resultInfo) {
//		
//		OrganizationBaseEntity baseEntityInfo = new OrganizationBaseEntity();
//	     JSONObject baseInfoJson = orgBaseService.findById(orgEntity.getBaseId());
//	     if (ResultPojo.CODE_SUCCESS.equals(baseInfoJson.getString("code"))) {
//	    	 baseEntityInfo =   JSONObject.toJavaObject(baseInfoJson.getJSONObject("result"), OrganizationBaseEntity.class);
//	    	 // 部门库的以下字段同步更新到部门基本信息表
//	    	 // 所属系统
//	    	 baseEntityInfo.setOwnSys(orgEntity.getOwnSys());
//	    	 // 部门名称
//	    	 baseEntityInfo.setName(orgEntity.getName());
//	    	 // 是否涉密
//	    	 baseEntityInfo.setIsSecret(orgEntity.getIsSecret());
//	    	 // 是否主管
//	    	 baseEntityInfo.setIsComp(orgEntity.getIsComp());
//	    	 // 主管部门
//	    	 if(!Contsants.OFS_ORG_STR_IS_COMP.equals(orgEntity.getIsComp())) {
//	    		 baseEntityInfo.setCompId(orgEntity.getParentId());
//	    	 }
//	    	 // 机构类别涉及到编制信息,不同步更新到（事业单位与行政机关编制信息不同）
//	    	 
//	      } else {
//	    	  resultInfo.setCode(baseInfoJson.getString("code"));
//	    	  resultInfo.setMsg( "部门基本信息表中以主键ID 【" + orgEntity.getBaseId()  + "】的" +  baseInfoJson.getString("msg"));
//	    	  resultInfo.setResult(null);
//	          return -1;
//	     }
//		 // 执行保存部门基本信息表
//	     JSONObject updateBaseInfoJson = orgBaseService.saveOrUpdate(baseEntityInfo, "1");
//   	      // 判断保存是否成功失败
//		  if (!ResultPojo.CODE_SUCCESS.equals(updateBaseInfoJson.getString("code")) ) {
//			  // 保存失败场合
//			  resultInfo.setCode(updateBaseInfoJson.getString("code"));
//			  resultInfo.setMsg("[orgBaseService.saveOrUpdate] in function of recUpdateOwnSys " + ResultPojo.MSG_FAILURE + "【"  + updateBaseInfoJson.getString("msg") + "】" );
//			  resultInfo.setResult(null);
//			  return  -1;
//		  } 
//		return 0;
//	}
}
